package com.hsd.netty.server.decoder;

import com.hsd.netty.server.common.NettyMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.msgpack.MessagePack;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *  将bytebuf的字节流转换成通用对象，通过messagePack，
 *  你可以使用json，protobuf等序列化产品来代替messagePack
 * @author s.he
 * on 2020/6/1
 */
@Service
@ChannelHandler.Sharable
public class MessagePackDecoder extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf msg, List<Object> out) throws Exception {
        final int length = msg.readableBytes();
        byte[] arrays = new byte[length];
        msg.getBytes(msg.readerIndex(), arrays, 0, length);
        MessagePack messagePack = new MessagePack();
        NettyMessage message = messagePack.read(arrays, NettyMessage.class);
        out.add(message);
    }
}
